package com.csu.chart;//import org.graalvm.compiler.phases.common.DeadCodeEliminationPhase;
import com.csu.consts.UiConsts;
import com.csu.ds.ExpdItem;
import com.csu.ds.AmountByMonth;
import com.csu.ds.ExpdClass;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.*;
import org.jfree.chart.renderer.xy.XYSplineRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

public class InfoChartStatics {

    public static CategoryDataset getBarDataset( ArrayList<AmountByMonth> amountByMonthList ){
        //创建数据集对象
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        AmountByMonth curAmountByMonth;
        for( int i = 0; i < amountByMonthList.size(); i ++ ){
            curAmountByMonth = amountByMonthList.get(i);
            double value = curAmountByMonth.getAmount();
            dataset.addValue( value, "A", (curAmountByMonth.getMonth() + 1)+""  );
        }

        return dataset;
    }

    public static PieDataset getPieDataset( ArrayList<ExpdItem> expd ) {
        ArrayList<ExpdClass> expdC = new ArrayList<>();
        boolean overlap = false;
        ExpdItem curExpdItem;
        ExpdClass curExpdClass;

        //获取当月时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new java.util.Date(System.currentTimeMillis()));
        int currentMonth = calendar.get(Calendar.MONTH); //currentMonth为当前月份-1(Month从0开始)

        //分析支出种类
        for( int i = 0; i < expd.size(); i ++ ){
            curExpdItem = expd.get(i);
            overlap = false;
            //判断是否为本月支出
            if( currentMonth != curExpdItem.getDate().getMonth() ){
                continue; //分析下一条支出项
            }

            for( int x = 0; x < expdC.size(); x ++ ){ //查看分类里是否已有该项
                curExpdClass = expdC.get(x);
                if(curExpdItem.getType().equals( curExpdClass.getType() )){ //已有该项
                    overlap = true;
                    curExpdClass.setAmount( curExpdClass.getAmount() + curExpdItem.getAmount() );
                    break;
                }
            }
            if( !overlap ){//如果不重合
                expdC.add(new ExpdClass( curExpdItem.getType(), curExpdItem.getAmount() ) );
            }
        }

        //创建数据集
        int num = expdC.size();//分块数等于支出种类的数目

        double amount_all = 0;//本月总支出

        //计算本月总支出
        for( int i = 0; i < num; i ++ ){
            amount_all += expdC.get(i).getAmount();
        }

        DefaultPieDataset dataset = new DefaultPieDataset();
        for( int i = 0; i < num; i ++ ){
            curExpdClass = expdC.get(i);
            dataset.setValue( curExpdClass.getType(), curExpdClass.getAmount() / amount_all  );
        }

        return dataset;

    }

    public static JFreeChart generateBarChart(CategoryDataset dataset, Color barColor) //用数据集创建一个图表
    {
        JFreeChart chart= ChartFactory.createBarChart("",
                "月",
                "",
                dataset,
                PlotOrientation.VERTICAL,
                false,
                false,
                false); //创建一个JFreeChart

        CategoryPlot cPlot=(CategoryPlot)chart.getPlot();//获得图标中间部分，即plot
        cPlot.setForegroundAlpha(1f); //图表柱条的透明度，1为不透明，0为透明
        cPlot.setBackgroundPaint(Color.WHITE);//画图区域的背景颜色
        cPlot.setOutlineVisible(false);

        CategoryAxis categoryAxis = cPlot.getDomainAxis();//获得横坐标
        categoryAxis.setLabelFont(new Font("Songti SC",Font.PLAIN,10));//设置横坐标字体
        categoryAxis.setMaximumCategoryLabelWidthRatio(1.5f);
//        categoryAxis.setTickLabelsVisible(false);
//        categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90); //设置字体90度旋转
//        categoryAxis.setVisible(false);
        NumberAxis numberaxis = (NumberAxis) cPlot.getRangeAxis();
        //Y轴增长单元设置
        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        numberaxis.setAutoRangeIncludesZero(true);// 起始坐标是否包括0
        // Y轴的标签设置
        numberaxis.setLabel(null);//通过实例化Chart的时候设置,实例化后可以通过该方法设置,null为不显示
        numberaxis.setVisible(false);

        //设置柱体渲染
        BarRenderer renderer = new BarRenderer(barColor);
        cPlot.setRenderer(renderer);
        cPlot.setAxisOffset( new org.jfree.chart.ui.RectangleInsets(0, 0, 0, 0) );


        return chart;
    }


    public static JFreeChart generateRingChart( PieDataset dataset ){
        JFreeChart ring = ChartFactory.createRingChart("",
                dataset,
                false,
                false,
                false
        );

        RingPlot rPlot = (RingPlot)ring.getPlot();
        rPlot.setBackgroundPaint(Color.WHITE);
        rPlot.setOutlineVisible(false);
        rPlot.setSectionDepth(0.4d); //设置环体宽度
//        rPlot.setShadowPaint(Color.LIGHT_GRAY);//设置阴影
        rPlot.setShadowPaint(null);
        //生成标签
        rPlot.setLabelGenerator( new StandardPieSectionLabelGenerator("{0}{2}"));//{0}代表分块的名称，{2}代表分块的百分比，引号内可任意组合字符串
        //设置标签
        rPlot.setLabelFont(UiConsts.FONT_TRANS_TYPE);
        rPlot.setLabelOutlinePaint(Color.WHITE);
        rPlot.setLabelShadowPaint(null);
        rPlot.setLabelBackgroundPaint(new Color(0,true));
        //设置分块颜色库
        rPlot.setDrawingSupplier( new DefaultDrawingSupplier(
                new Paint[]{
                        new Color(161,197,223),
                        new Color(247,224,217),
                        new Color(175,210,207),
                        new Color(242,179,182),
                        new Color(233,234,240)
                },
                DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE
        ));

        return ring;

    }

    public static XYDataset getAssetDataset( ArrayList<AmountByMonth> assetByMonth ){
        TimeSeries timeseries = new TimeSeries("总资产");
        int lastYear = 2020;
        int thisYear = 2021;
        int year = lastYear;
        for( int i = 0; i < assetByMonth.size(); i ++ ){
            boolean crossYear = false;
            AmountByMonth curAssetByMonth = assetByMonth.get(i);
            if( i + 1 < assetByMonth.size() && curAssetByMonth.getMonth() > assetByMonth.get(i+1).getMonth()){
                crossYear = true;
            }

            //Month的构造函数里第一个参数month的值从1开始，而不是从0开始
            timeseries.add( new Month( curAssetByMonth.getMonth() + 1, year ), curAssetByMonth.getAmount() );
            if(crossYear){
                year = thisYear;
            }
//            timeseries.add( new Month( i, 2020 ), curAssetByMonth.getAmount() );
        }

        TimeSeriesCollection timeseriescollection = new TimeSeriesCollection();
        timeseriescollection.addSeries(timeseries);
        return timeseriescollection;
    }



    public static JFreeChart generateCurveChart( XYDataset dataset ){
        XYSplineRenderer renderer = new XYSplineRenderer();
        renderer.setPrecision(15); //设置精度，在源数据两个点之间插入n个点以拟合出一条平滑曲线
        renderer.setSeriesPaint(0, UiConsts.COLOR_NAVY_BLUE); //设置0号数据的颜色。这是手工设置线条颜色的方法
        renderer.setSeriesStroke( 0, new BasicStroke(3.5F) );
        renderer.setSeriesShapesVisible(0, false);//设置数据点不可见

        //create plot
        NumberAxis xAxis = new NumberAxis("月");
        xAxis.setAutoRangeIncludesZero(false);

        NumberAxis yAxis = new NumberAxis();
        yAxis.setAutoRangeIncludesZero(false);
        yAxis.setVisible(false);


        XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
        plot.setBackgroundPaint(Color.WHITE);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
        plot.setOutlineVisible(false);
        plot.setAxisOffset(new org.jfree.chart.ui.RectangleInsets(0,0,0,0)); //设置坐标轴与绘图区域的距离

        JFreeChart chart = new JFreeChart("",
                null,
                plot,
                false
        );

        //设置X轴的显示格式
        XYPlot xyplot = chart.getXYPlot();
        xyplot.setForegroundAlpha(0.8f);
        DateAxis dateAxis = new DateAxis( "时间 ");
        dateAxis.setDateFormatOverride(new SimpleDateFormat("M"));
        dateAxis.setAutoRange(true);
        dateAxis.setTickLabelsVisible(false);
        dateAxis.setVisible(false);
//        dateAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
        xyplot.setDomainAxis(dateAxis);

        chart.setBorderVisible(false);
        chart.setBackgroundPaint(Color.white);
        chart.setBorderStroke(new BasicStroke(0));

        return chart;

    }
}
